// 统计管理文件 - 包含统计相关的所有功能

import { STATE, StateManager } from './state.js';
import { CommonUtils } from './utils.js';

// 统计管理器
export const StatisticsManager = {
    // 切换界面
    switchView(view) {
        StateManager.setCurrentView(view);
        
        const bettingViewBtn = document.getElementById('bettingViewBtn');
        const statisticsViewBtn = document.getElementById('statisticsViewBtn');
        const bettingContent = document.getElementById('bettingContent');
        const statisticsContent = document.getElementById('statisticsContent');
        const bettingInfo = document.getElementById('bettingInfo');
        const bettingList = document.querySelector('.betting-list');
        
        if (view === 'betting') {
            // 切换到投注界面
            bettingViewBtn.classList.add('active');
            statisticsViewBtn.classList.remove('active');
            bettingContent.style.display = 'block';
            statisticsContent.style.display = 'none';
            bettingInfo.style.display = 'block';
            bettingList.style.display = 'block';
        } else {
            // 切换到统计界面
            bettingViewBtn.classList.remove('active');
            statisticsViewBtn.classList.add('active');
            bettingContent.style.display = 'none';
            statisticsContent.style.display = 'block';
            bettingInfo.style.display = 'none';
            bettingList.style.display = 'none';
            
            // 更新统计数据显示
            this.updateStatisticsDisplay();
        }
    },

    // 更新统计数据显示
    updateStatisticsDisplay() {
        // 更新今日统计
        const todayBetCount = document.getElementById('todayBetCount');
        const todayBetAmount = document.getElementById('todayBetAmount');
        const todayWinCount = document.getElementById('todayWinCount');
        const todayWinAmount = document.getElementById('todayWinAmount');
        const todayProfit = document.getElementById('todayProfit');
        
        if (todayBetCount) todayBetCount.textContent = STATE.statisticsData.today.betCount;
        if (todayBetAmount) todayBetAmount.textContent = `¥${STATE.statisticsData.today.betAmount}`;
        if (todayWinCount) todayWinCount.textContent = STATE.statisticsData.today.winCount;
        if (todayWinAmount) todayWinAmount.textContent = `¥${STATE.statisticsData.today.winAmount}`;
        
        if (todayProfit) {
            const profit = STATE.statisticsData.today.winAmount - STATE.statisticsData.today.betAmount;
            todayProfit.textContent = `¥${profit}`;
            todayProfit.className = profit >= 0 ? 'stat-value profit' : 'stat-value loss';
        }
        
        // 更新热门号码
        this.updateHotNumbers();
        
        // 更新投注偏好
        this.updatePreferences();
        
        // 更新历史记录
        this.updateHistoryDisplay();
    },

    // 更新热门号码显示
    updateHotNumbers() {
        const hotNumbersContainer = document.getElementById('hotNumbers');
        if (!hotNumbersContainer) return;
        
        // 获取热门号码（按投注次数排序）
        const sortedNumbers = Object.entries(STATE.statisticsData.hotNumbers)
            .sort(([,a], [,b]) => b - a)
            .slice(0, 4);
        
        if (sortedNumbers.length === 0) {
            hotNumbersContainer.innerHTML = '<div style="text-align: center; color: #6c757d;">暂无数据</div>';
            return;
        }
        
        hotNumbersContainer.innerHTML = sortedNumbers.map(([number, count]) => `
            <div class="hot-number-item">
                <span class="number">${number.padStart(2, '0')}</span>
                <span class="count">${count}次</span>
            </div>
        `).join('');
    },

    // 更新投注偏好显示
    updatePreferences() {
        const total = Object.values(STATE.statisticsData.preferences).reduce((sum, count) => sum + count, 0);
        
        if (total === 0) return;
        
        const preferences = [
            { key: 'tema_zhixuan', label: '特码直选', element: document.querySelector('.preference-item:nth-child(1)') },
            { key: 'tema_liangmian', label: '特码两面', element: document.querySelector('.preference-item:nth-child(2)') },
            { key: 'zhengma_renxuan', label: '正码任选', element: document.querySelector('.preference-item:nth-child(3)') }
        ];
        
        preferences.forEach(({ key, element }) => {
            if (element) {
                const count = STATE.statisticsData.preferences[key];
                const percentage = Math.round((count / total) * 100);
                const fillElement = element.querySelector('.preference-fill');
                const percentElement = element.querySelector('.preference-percent');
                
                if (fillElement) fillElement.style.width = `${percentage}%`;
                if (percentElement) percentElement.textContent = `${percentage}%`;
            }
        });
    },

    // 更新历史记录显示
    updateHistoryDisplay() {
        const historyList = document.getElementById('historyList');
        if (!historyList) return;
        
        if (STATE.statisticsData.history.length === 0) {
            historyList.innerHTML = '<div style="text-align: center; color: #6c757d; padding: 20px;">暂无投注记录</div>';
            return;
        }
        
        historyList.innerHTML = STATE.statisticsData.history.slice(-10).reverse().map(record => {
            // 解析赔率信息，显示平均赔率或最高赔率
            let oddsDisplay = '1.0';
            if (record.odds) {
                const oddsArray = record.odds.split(';').map(item => {
                    const parts = item.split(':');
                    return parts.length > 1 ? parseFloat(parts[1]) : 1.0;
                }).filter(odds => !isNaN(odds));
                
                if (oddsArray.length > 0) {
                    if (oddsArray.length === 1) {
                        oddsDisplay = oddsArray[0].toFixed(2);
                    } else {
                        // 多个投注显示平均赔率
                        const avgOdds = oddsArray.reduce((sum, odds) => sum + odds, 0) / oddsArray.length;
                        oddsDisplay = avgOdds.toFixed(2);
                    }
                }
            }
            
            return `
                <div class="history-item">
                    <span>${record.time}</span>
                    <span>${record.lottery}</span>
                    <span>${record.gameType}</span>
                    <span title="${record.odds || '无赔率信息'}">${record.content}</span>
                    <span title="平均赔率">${oddsDisplay}</span>
                    <span>¥${record.amount}</span>
                    <span class="status ${record.status}">${CommonUtils.getStatusText(record.status)}</span>
                </div>
            `;
        }).join('');
    },

    // 添加投注记录到统计
    addBetToStatistics(betData) {
        // 更新今日统计
        STATE.statisticsData.today.betCount++;
        STATE.statisticsData.today.betAmount += betData.totalAmount;
        
        // 更新热门号码
        if (betData.numbers) {
            betData.numbers.forEach(number => {
                STATE.statisticsData.hotNumbers[number] = (STATE.statisticsData.hotNumbers[number] || 0) + 1;
            });
        }
        
        // 更新投注偏好
        const preferenceKey = `${betData.game}_${betData.sub}`;
        if (STATE.statisticsData.preferences.hasOwnProperty(preferenceKey)) {
            STATE.statisticsData.preferences[preferenceKey]++;
        }
        
        // 添加历史记录
        const now = new Date();
        const record = {
            time: now.toLocaleTimeString('zh-CN', { hour12: false }),
            lottery: CommonUtils.getLotteryName(STATE.currentLottery),
            gameType: betData.gameType,
            content: betData.content,
            amount: betData.totalAmount,
            odds: betData.odds,
            betDetails: betData.betDetails,
            status: 'pending'
        };
        
        STATE.statisticsData.history.push(record);
        
        // 保存到本地存储
        this.saveStatisticsData();
    },

    // 清空历史记录
    clearHistory() {
        if (confirm('确定要清空所有历史记录吗？')) {
            STATE.statisticsData.history = [];
            STATE.statisticsData.today = {
                betCount: 0,
                betAmount: 0,
                winCount: 0,
                winAmount: 0
            };
            STATE.statisticsData.hotNumbers = {};
            STATE.statisticsData.preferences = {
                tema_zhixuan: 0,
                tema_liangmian: 0,
                zhengma_renxuan: 0
            };
            
            // 清空赔率历史
            STATE.oddsHistory = {};
            
            this.saveStatisticsData();
            this.updateStatisticsDisplay();
            alert('历史记录已清空');
        }
    },

    // 保存统计数据到本地存储
    saveStatisticsData() {
        try {
            const dataToSave = {
                statisticsData: STATE.statisticsData,
                oddsHistory: STATE.oddsHistory
            };
            localStorage.setItem('lhc_statistics', JSON.stringify(dataToSave));
        } catch (e) {
            console.warn('无法保存统计数据到本地存储:', e);
        }
    },

    // 从本地存储加载统计数据
    loadStatisticsData() {
        try {
            const saved = localStorage.getItem('lhc_statistics');
            if (saved) {
                const data = JSON.parse(saved);
                
                // 兼容旧版本数据格式
                if (data.statisticsData) {
                    // 新版本格式
                    STATE.statisticsData = {
                        ...STATE.statisticsData,
                        ...data.statisticsData,
                        today: { ...STATE.statisticsData.today, ...data.statisticsData.today },
                        preferences: { ...STATE.statisticsData.preferences, ...data.statisticsData.preferences }
                    };
                    STATE.oddsHistory = data.oddsHistory || {};
                } else {
                    // 旧版本格式（只有统计数据）
                    STATE.statisticsData = {
                        ...STATE.statisticsData,
                        ...data,
                        today: { ...STATE.statisticsData.today, ...data.today },
                        preferences: { ...STATE.statisticsData.preferences, ...data.preferences }
                    };
                }
            }
        } catch (e) {
            console.warn('无法从本地存储加载统计数据:', e);
        }
    }
}; 